package com.kgc.xsConsumer.controller;

import com.kgc.basic.util.ResponseMsg;
import com.kgc.xs.remote.SalesOrderExecutionStatusRemote;
import com.kgc.xsConsumer.feign.ImportExportFeign;
import com.kgc.xsConsumer.feign.SalesOrderExecutionStatusFeign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Map;

@RestController
@RequestMapping("/salesOrderExecutionStatus")
@CrossOrigin
public class SalesOrderExecutionStatusController {

    private Logger logger = LoggerFactory.getLogger(SalesOrderExecutionStatusController.class);

    @Autowired
    private SalesOrderExecutionStatusFeign salesOrderExecutionStatusFeign;

    @Autowired
    private ImportExportFeign importExportFeign;

    @RequestMapping("selectByPage")
    public ResponseMsg selectByPage(@RequestBody Map<String, Object> map) {
        logger.info("consumer SalesOrderExecutionStatusController selectByPage map:{}", map);
        return salesOrderExecutionStatusFeign.selectSalesOrderExecutionStatusByPage(map);
    }

    //导出
    @RequestMapping(value = "/export")
    public void exportCustomers(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        logger.info("consumer SalesOrderExecutionStatusController exportCustomers params:{}", map);
        try {
            ResponseMsg responseMsg = importExportFeign.exportEntities(map, "com.kgc.xs.pojo.SalesOrderExecutionStatus", "codeDate desc");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] exportData = Base64.getDecoder().decode(base64Data);

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("销售订单执行情况表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(exportData);
            } else {
                logger.error("导出失败, msg: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer SalesOrderExecutionStatusController exportCustomers is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}
